package com.doubletick.proxy.ipidea.task;

import cn.hutool.core.util.StrUtil;
import com.doubletick.proxy.ipidea.cache.ProxyAccountConsumedFlowCache;
import com.doubletick.proxy.ipidea.domain.ProxyAccount;
import com.doubletick.proxy.ipidea.manager.IProxyAccountManager;
import com.doubletick.proxy.ipidea.service.IProxyAccountService;
import com.doubletick.proxy.ipidea.service.IProxyFlowChargeHistoryService;
import com.doubletick.proxy.ipidea.util.ProxyAccountUtil;
import com.doubletick.proxy.ipidea.util.ProxyFlowUtil;
import com.doubletick.proxy.ipidea.util.dto.account.ProxyAccountResult;
import com.doubletick.proxy.ipidea.util.dto.flow.FlowUserRecord;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;

@Slf4j
@Component
public class ProxyTask {
    @Resource
    private IProxyAccountService proxyAccountService;


    @Resource
    private IProxyAccountManager proxyAccountManager;


    @Resource
    private IProxyFlowChargeHistoryService flowChargeHistoryService;

    public static List<ProxyAccountResult> queryFlowDetailist;
    @Resource
    private ProxyAccountConsumedFlowCache consumedFlowCache;

    //更新流量
    public void reloadConsumerFlow() {
        List<ProxyAccountResult> thirdAccountList = ProxyAccountUtil.list();
        if (CollectionUtils.isEmpty(thirdAccountList)) {
            return;
        }
        queryFlowDetailist = thirdAccountList;
        log.info("reloadConsumerFlow:{}", queryFlowDetailist == null ? -1 : queryFlowDetailist.size());
        thirdAccountList.forEach(account -> {
            ProxyAccount proxyAccount = proxyAccountService.selectByProxyIdOrAccount(account.getId(), account.getAccount());
            if (proxyAccount == null) {
                //没有流量消耗的不管
                boolean isGreaterThanZero = account.getConsumed_flow().compareTo(BigDecimal.ZERO) > 0;
                if (!isGreaterThanZero) {
                    return;
                }
                log.info("没找到对应的直接插入:{}:{}", account.getAccount(), account.getConsumed_flow());
                ProxyAccount insert = new ProxyAccount();
                insert.setAccount(account.getAccount());
                insert.setProxyId(account.getId());
                insert.setLimitFlow(account.getLimit_flow().toPlainString());
                insert.setConsumedFlow(account.getConsumed_flow());
                insert.setState(String.valueOf(account.getState()));
                insert.setRemark(String.valueOf(account.getRemark()));
                proxyAccountService.insertProxyAccount(insert);
                return;
            }
            ProxyAccount update = new ProxyAccount();
            log.info("{}:{}", account.getAccount(), account.getConsumed_flow());
            update.setConsumedFlow(account.getConsumed_flow());
            if (StrUtil.isEmpty(proxyAccount.getProxyId())) {
                update.setProxyId(account.getId());
                // 修改流量历史里面的数据
                flowChargeHistoryService.updateProxyIdByUserId(update.getProxyId(), proxyAccount.getUserId());
            }
            update.setId(proxyAccount.getId());
            if (proxyAccount.getUserId() == null) {
                update.setLimitFlow(account.getLimit_flow().divide(new BigDecimal("1000000")).toPlainString());
            }
            proxyAccountService.updateFlowById(update);
        });
    }

    @SneakyThrows
    public void queryFlowDetail() {//proxyTask.queryFlowDetail
        log.info("queryFlowDetail:{}", queryFlowDetailist == null ? -1 : queryFlowDetailist.size());
        if (CollectionUtils.isEmpty(queryFlowDetailist)) {
            return;
        }
        Collections.shuffle(queryFlowDetailist);
        for (ProxyAccountResult account : queryFlowDetailist) {
            if (account.getConsumed_flow() == null || account.getConsumed_flow().compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            String proxyId = account.getId();
            BigDecimal bigDecimal = consumedFlowCache.getConsumedFlow(proxyId);
            if (bigDecimal != null && bigDecimal.compareTo(account.getConsumed_flow()) == 0) {
                continue;
            }
            try {
                //查询记录
                int days = 31;
                List<FlowUserRecord> flowList = ProxyFlowUtil.proxyAccountUseRecord(days, proxyId);
                boolean exec = false;
                if (!CollectionUtils.isEmpty(flowList)) {
                    exec = proxyAccountManager.saveList(account, flowList);
                }
                if (exec) {
                    consumedFlowCache.putCache(proxyId, account.getConsumed_flow());
                }
            } catch (Exception e) {
                log.error("queryFlowDetail:" + proxyId + ":" + account.getAccount(), e);
            }
        }
    }

}
